package com.cn.wanxi.servlet.back;
import com.cn.wanxi.model.DataField;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/back/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect(DataField.LOCALHOST_PORT+"/html/back/register.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String code = ((String) req.getSession().getAttribute("code")).toLowerCase();
        String iptcode = req.getParameter("codeipt").toLowerCase();
        int result = 0;
        if (code.equals(iptcode)) {
            IUserService userService = new UserServiceImpl();
            UserModel user = new UserModel();
            user.setUsername(req.getParameter("username"));
            user.setPassword(req.getParameter("password"));
            user.setPhone(req.getParameter("phone"));
            user.setSex(req.getParameter("sex"));
            user.setIntro(req.getParameter("intro"));
            user.setBirth(req.getParameter("birth"));
            user.setHobby(req.getParameter("hobby"));
            user.setCreate_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date().getTime()));
            result = userService.addUser(user);
        }
        resp.getWriter().print(result);
    }
}
